Interfaces and Packages

1. Interfaces in Java

An interface is a blueprint for a class that defines a set of abstract methods. Interfaces are implemented by classes using the implements keyword.

Creating and Implementing an Interface

    
    // Defining an interface
    interface Vehicle {
        void start(); // Abstract method (no body)
        void stop();  // Abstract method
    }
    
    // Implementing the interface
    class Car implements Vehicle {
        public void start() {
            System.out.println("Car is starting");
        }
        public void stop() {
            System.out.println("Car has stopped");
        }
    }
    
    class Main {
        public static void main(String[] args) {
            Car myCar = new Car();
            myCar.start();
            myCar.stop();
        }
    }
    
    

Key Features of Interfaces

Difference Between Abstract Class and Interface

2. Packages in Java

A package is a collection of related classes and interfaces. It helps in organizing the code and avoids class name conflicts.

Creating a Package

    
    // Creating a package
    package mypackage;
    
    public class Example {
        public void display() {
            System.out.println("This is a package example");
        }
    }
    
    

Importing a Package

To use a class from another package, use the import keyword.

    
    import mypackage.Example; // Importing specific class
    
    class Main {
        public static void main(String[] args) {
            Example obj = new Example();
            obj.display();
        }
    }
    
    

Types of Packages

3. Viva/Interview Questions

An interface is used to achieve abstraction and multiple inheritance.
No, interfaces cannot have constructors because they cannot be instantiated.
An abstract class can have both abstract and concrete methods, while an interface can only have abstract methods (before Java 8).
A package is a namespace that organizes related classes and interfaces to avoid conflicts.
Use the syntax import packageName.*;
Regular import imports classes, while static import allows importing static members directly.